<template>
  <el-container>
    <el-header>
      <el-row >
        <el-col :span="4">
          <h1 >运动器材</h1>
        </el-col>
          <el-col :span="2" :offset="14" style="margin-top:36px">
            <el-badge v-if="bagNumber>0" :value="bagNumber">
              <el-link style="font-size:16px" type="primary" @click="openBag"><i class="el-icon-shopping-bag-1"></i>器材袋</el-link>
            </el-badge>
            <el-link v-else style="font-size:16px" type="primary" @click="openBag"><i class="el-icon-shopping-bag-1"></i>器材袋</el-link>
          </el-col>
          <el-col :span="4" style="margin-top:30px">
            <my-Search :searchWay="true" :inputNoOptionSpan="24" :inputPlaceholder="'器材名称'" @onSearch="getSearchContent"></my-Search>
          </el-col>
      </el-row>
    </el-header>
    <el-main>
      <el-tabs tab-position="left" @tab-click="tabClick" :lazy="true">
        <el-tab-pane v-for="(item,index) in categories" :key="item.id" :name="index.toString()" :label="item.label">
          <el-empty v-if="equipmentListData.length==0" description="未找到符合条件的器材" :image-size="300" :image="notFoundEquipmentPic"></el-empty>
          <el-row v-if="equipmentListData.length>0" :gutter="30" class="listRow">
            <el-col :lg="4" :md="8" :xs="12"  v-for="e in equipmentListData" :key="e.id">
                <div class="card" @click="showEquipmentDetails(e)">
                  <el-row>
                    <div class="fieldCover"
                      :style="
                      'background-image:linear-gradient(to top, rgba(255, 255, 255,1),rgba(255, 255, 255, 0),rgba(255, 255, 255, 0),rgba(255, 255, 255, 0),rgba(255, 255, 255, 0)),url('+e.url+');'
                      ">
                    </div>
                  </el-row>
                  <el-row class="eInfo">
                    <div class="eTitle">{{e.name}}</div>
                    <el-row>
                      <el-col :span="12" v-if="e.buyCost>=0" class="buyprice">
                        <div class="buycost">售</div>{{e.buyCost}}<span> 元</span>
                      </el-col>
                      <el-col :span="12" v-if="e.rentCost>=0" class="rentprice">
                        <div class="rentcost">租</div>{{e.rentCost}}<span> 元/时</span>
                      </el-col>
                    </el-row>
                  </el-row>
                </div>
            </el-col>
          </el-row>
          <el-row v-if="equipmentListData.length>0">
            <pagination
            ref="pagination"
            @pagination="getPagination"
            :total="parseInt(totalPage)"
            :page="parseInt(searchCondition.page)"
            :limit="parseInt(searchCondition.pageSize)"
            :pageSizes="paginationSize"
            ></pagination>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-main>
    <el-dialog
      ref="DDialogRef"
      :title="DDialog.title"
      :width="DDialog.width+'px'"
      :visible.sync="DDialog.visible"
      :before-close="onClose"
      :closeOnClickModal="false"
      append-to-body
    >
      <el-row :style="{ minHeight: DDialog.height + 'px' }">
        <el-col :span="10" :offset="1">
          <el-row>
            <el-carousel
            style="width:300px"
              :interval="5000"
              :arrow="picList.length==1 ? 'never':'hover'"
              :indicator-position="picList.length==1 ? 'none':'outside'"
              :autoplay="picList.length>1"
            >
              <el-carousel-item v-for="(pic,index) in picList" :key="index">
                  <div class="fieldPic" :style=" 'background-image:url('+pic+');' "></div>
              </el-carousel-item>
            </el-carousel>
          </el-row>
          <el-row>
            <h2 class="infoTitle">{{equipmentInfo.name}}</h2>
            <p class="infoRemark"><span>器材位置：</span>{{equipmentInfo.local}}</p>
            <p class="infoRemark"><span>器材简介：</span>{{equipmentInfo.remark}}</p>
          </el-row>
        </el-col>
        <el-col :span="11" :offset="1">
          <el-tabs :lazy="true" type="border-card" :value="equipmentInfo.rentCost>=0 ? 'rent':'buy'">
            <el-tab-pane v-if="equipmentInfo.rentCost>=0" label="租借" name="rent">
              <el-form size="medium" ref="rentFormRef" :model="rentFormData" label-width="80px" class="formStyle" :rules="rentRules">
                <el-form-item label="库存数量">
                  <span>{{equipmentInfo.number}}</span>
                </el-form-item>
                <el-form-item label="租借费用">
                  <span style="color:red;font-weight:bold;">{{equipmentInfo.rentCost}}</span><span style="font-size:16px"> 元/时</span>
                </el-form-item>
                <el-form-item prop="rentNumber" label="租借数量">
                  <el-input-number size="mini" v-model.number="rentFormData.rentNumber" :min="1" :max="equipmentInfo.number"></el-input-number>
                </el-form-item>
                <el-form-item prop="rent" label="租借时长">
                  <el-input-number size="mini" v-model.number="rentFormData.rent" :min="1" :max="72"></el-input-number>
                </el-form-item>
                <el-form-item prop="getTime" label="租取时间">
                  <el-time-picker
                    size="small"
                    v-model="rentFormData.getTime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :picker-options="{
                      selectableRange:timeRange
                    }"
                    placeholder="今天何时租取器材">
                  </el-time-picker>
                </el-form-item>

                <el-form-item label="预计费用">
                  <span style="color:red;font-weight:bold;">{{rentPay}}</span><span style="font-size:16px"> 元</span>
                </el-form-item>
                <el-form-item style="text-align:right;">
                  <!-- <el-button type="success" @click="conRent">确定租借</el-button> -->
                  <el-button type="success" @click="checkOutTime(0)">确定租借</el-button>
                </el-form-item>
                 <el-alert title="租借时长每24小时内每小时租借费用减半" type="info" show-icon />
              </el-form>
            </el-tab-pane>
            <el-tab-pane v-if="equipmentInfo.buyCost>=0" label="购买" name="buy">
              <el-form size="medium" label-width="80px" ref="buyFormRef" :model="buyFormData" class="formStyle" @submit.native.prevent :rules="buyRules">
                <el-form-item label="库存数量">
                  <span>{{equipmentInfo.number}}</span>
                </el-form-item>
                <el-form-item label="器材单价">
                  <span style="color:red;font-weight:bold;">{{equipmentInfo.buyCost}}</span><span style="font-size:16px"> 元</span>
                </el-form-item>
                <el-form-item prop="buy" label="购买数量">
                  <el-input-number size="mini" v-model.number="buyFormData.buy" :min="1" :max="equipmentInfo.number"></el-input-number>
                </el-form-item>
                <el-form-item label="预计费用">
                  <span style="color:red;font-weight:bold;">{{buyPay}}</span><span style="font-size:16px"> 元</span>
                </el-form-item>
                <el-form-item style="text-align:right;">
                  <el-button type="primary" @click="putBag" >放入器材袋</el-button>
                  <!-- <el-button type="success" @click="conBuy">立即购买</el-button> -->
                  <el-button type="success" @click="checkOutTime(1)">立即购买</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </el-dialog>
    <!-- 确认订单 -->
    <my-dialog
      :title="ordersDialog.title"
      :width="ordersDialog.width"
      :height="ordersDialog.height"
      :visible="ordersDialog.visible"
      @onClose="onOrdersClose"
      @onConfirm="onOrdersConfirm"
    >
      <div slot="content">
        <div v-if="!orderType">
          <el-alert show-icon :title="ordersAlertTitle" type="success" :closable="false" />
          <el-form size="lar" label-width="80px" @submit.native.prevent class="formStyle">
            <el-form-item label="器材名称"><span style="color:#303133;font-weight:bold;">{{equipmentInfo.name}}</span></el-form-item>
            <el-form-item label="租借费用"><span style="color:red;">{{equipmentInfo.rentCost | showCost}} /时</span></el-form-item>
            <el-form-item label="租借数量"><span>{{backRentInfo.number}}</span></el-form-item>
            <el-form-item label="租借时长"><span>{{backRentInfo.times | showTime}}</span></el-form-item>
            <el-form-item v-if="point==0||point==null" label="租借花费"><span style="color:red;">{{backRentInfo.cost | showCost}}</span></el-form-item>
            <el-form-item v-if="point>0&&point!=null" label="租借花费">
              <span style="color:#909399;font-size:20px;text-decoration: line-through;">{{backRentInfo.cost | showCost}}</span>
              <span style="color:red;margin-left:10px;">{{allCost | showCost}}</span>
            </el-form-item>
            <el-form-item v-if="allPoint>0&&this.backRentInfo.cost>0" label="使用积分">
              <el-input-number v-model="point" :step="100" size="mini" :min="0" :max="canUsePoint"></el-input-number>
            </el-form-item>
          </el-form>
          <div v-if="allPoint>0&&this.backRentInfo.cost>0">
            <el-alert v-if="point==0||point==null" show-icon :title="'可使用'+canUsePoint+'积分抵扣'+canUsePoint/1000+'元'" type="warning" :closable="false" />
            <el-alert v-if="point>0&&point!=null" show-icon :title="'已使用'+point+'积分抵扣'+point/1000+'元'" type="success" :closable="false" />
          </div>
        </div>
        <div v-if="orderType">
          <el-alert show-icon :title="ordersAlertTitle" :type="ordersAlertType" :closable="false" />
          <el-table
            :data="backBuyInfo"
            :summary-method="getSummaries"
            show-summary
          >
            <el-table-column type="index" align="center" width="70"></el-table-column>
            <el-table-column prop="name" align="center" label="器材图片">
              <template  slot-scope="scope">
                <div style="width:80px;height:80px;margin:0 auto;">
                  <el-image :src="scope.row.cover" >
                    <div slot="error">
                      <i class="el-icon-picture-outline"></i>
                    </div>
                  </el-image>
                </div>

              </template>
            </el-table-column>
            <el-table-column prop="name" align="center" label="器材名称" show-overflow-tooltip></el-table-column>
            <el-table-column prop="count" align="center" label="购买数量"></el-table-column>
            <el-table-column prop="price" align="center" label="器材单价">
              <template  slot-scope="scope">
                {{scope.row.price | showCost}}
              </template>
            </el-table-column>
            <el-table-column prop="cost" align="right" label="价格">
              <template  slot-scope="scope">
                {{scope.row.cost | showCost}}
              </template>
            </el-table-column>
          </el-table>
          <div v-if="allPoint>0&&allBuyCost>0||point>0" style="text-align:right;margin-top:20px">
            <el-popover
              placement="left"
              width="100"
              trigger="click"
            >
              <el-input-number v-model="point" :step="100" size="mini" :min="0" :max="canUsePoint"></el-input-number>
              <el-link v-if="point==0||point==null" slot="reference" type="warning">可使用{{canUsePoint}}积分抵扣{{canUsePoint/1000}}元</el-link>
              <el-link v-if="point>0&&point!=null" slot="reference" type="success">使用{{point}}积分抵扣{{point/1000}}元</el-link>
            </el-popover>
          </div>
        </div>
      </div>
    </my-dialog>
    <!-- 支付弹框 -->
    <my-dialog
      ref="payDialogRef"
      :title="payDialog.title"
      :width="payDialog.width"
      :height="payDialog.height"
      :visible="payDialog.visible"
      @onClose="onPayClose"
      @onConfirm="onPayConfirm"
    >
      <div slot="content">
        <el-result v-if="!orderType&&balance<allCost||orderType&&balance<allBuyCost" icon="warning" title="余额不足">
          <template slot="extra">
            <router-link :to="'/account/accountSafe'">
              <el-link type="primary">前往充值</el-link>
            </router-link>
          </template>
        </el-result>
        <div v-else>
          <h1 style="color:red;text-align:center;">¥ {{paycost}}</h1>
          <el-statistic
            class="tiptext"
            ref="statistic"
            format="m:ss"
            prefix="下单成功! 请在"
            suffix="时间内完成订单支付"
            :value="ordersStopCountDown"
            time-indices
          />
          <my-valid-input :type="true" @giveInputValue="getPayInputValue" ref="payInputRef"></my-valid-input>
          <el-row v-if="payCount>=3" style="margin-top:20px">
            <el-col :span="7" :offset="6">
              <el-input v-model="payCode" placeholder="输入正确结果" clearable />
            </el-col>
            <el-col :span="5" :offset="1">
              <el-image :src="codeImage" @click="getMathCodeImage" class="codeImg"></el-image>
            </el-col>
          </el-row>
        </div>
      </div>
    </my-dialog>
    <!-- 器材袋 -->
    <el-dialog
      ref="BagDialogRef"
      :title="bagDialog.title"
      :width="bagDialog.width+'px'"
      :visible.sync="bagDialog.visible"
      :before-close="onbagClose"
      :closeOnClickModal="false"
      append-to-body
    >
      <el-row :style="{ minHeight: bagDialog.height + 'px' }">
        <el-table
          ref="bagRef"
          @selection-change="selectTable"
          row-key="id"
          :data="bagList"
        >
          <el-table-column type="selection" align="center" width="55"></el-table-column>
          <el-table-column prop="name" align="center" label="器材图片">
            <template  slot-scope="scope">
              <div style="width:80px;height:80px;margin:0 auto;">
                <el-image :src="scope.row.cover" >
                  <div slot="error">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
              </div>

            </template>
          </el-table-column>
          <el-table-column prop="name" align="center" label="器材名称" show-overflow-tooltip></el-table-column>
          <el-table-column prop="price" align="center" label="器材单价">
            <template  slot-scope="scope">
              {{scope.row.price | showCost}}
            </template>
          </el-table-column>
          <el-table-column width="140" prop="number" align="center" label="购买数量">
            <template  slot-scope="scope">
              <el-input-number @change="changeCount(scope.row)" size="mini" :min="1" :max="scope.row.count" v-model="scope.row.number"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column prop="count" align="center" label="库存"></el-table-column>
          <el-table-column prop="cost" align="center" label="价格">
            <template  slot-scope="scope">
              {{scope.row.cost | bagShowCost(scope.row)}}
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <el-row type="flex" justify="space-between" align="middle">
        <el-col :span="6" class="countCost">
          <span style="font-size:16px;color:#909399;">预计花费:</span>
          <count-to
            v-if="!isNaN(bagListCost)"
            :start-val="bagListCost"
            :end-val="bagListCost"
            :decimals="2"
            separator=","
            prefix="¥ "
          />
        </el-col>
        <el-col style="text-align:right" :span="8">
          <el-button :disabled="selectTableRow.length==0" type="danger" @click="deleteBag(true)" :loading="ordersDialog.visible">移出器材袋</el-button>
          <!-- <el-button :disabled="selectTableRow.length==0||isNaN(bagListCost)" type="success" @click="onbagConfirm">确认购买</el-button> -->
          <el-button :disabled="selectTableRow.length==0||isNaN(bagListCost)" type="success" @click="checkOutTime(2)" :loading="ordersDialog.visible">确认购买</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </el-container>
</template>

<script>
import { getPicturesByBidApi } from "@/api/pictures";
import { getAssetByUid, checkAssetKeyApi } from "@/api/asset";
import { addNewOrdersApi,finishPayApi } from "@/api/orders";
import { getMathCodeImageApi, checkMathCodeApi} from "@/api/captcha";
import {
  getValidEquipmentListApi,
  checkOutTimeApi,
  getEquipmentApi,
  addEquipmentRentApi,
  deleteEQRentApi,
  addEquipmentBuyApi,
  deleteEQBuyApi,
  getEquipmentBagInfoApi,
  getEquipmentBagNumberApi,
  addEquipmentBagApi,
  editEquipmentBagApi,
  deleteBagApi,
} from "@/api/equipment";
import countTo from 'vue-count-to';
import myValidInput from '@/components/MyValidInput';
import myDialog from "@/components/MyDialog/index";
import mySearch from "@/components/MySearch/index";
import pagination from "@/components/Pagination/index";
import notFoundEquipmentPic from "@/assets/other_images/NotFoundEquipment.png";
  export default {
    components: { myDialog,mySearch,pagination,myValidInput,countTo },
    data(){
      return{
        //使用积分后显示的金额值
        paycost:0,

        //选中的器材项
        selectTableRow: [],
        //器材袋信息
        bagList:[],
        //器材袋弹框
        bagDialog:{
          title:'器材袋',
          width:920,
          height:600,
          visible: false
        },
        //器材袋的数量
        bagNumber:0,

        //完成建立订单后的返回
        newOrders:'',
        //支付弹框
        payDialog: {
          title: "支付订单",
          width: 500,
          height: 120,
          visible: false
        },
        //订单倒计时
        ordersStopCountDown: 0,
        //支付密码输入框
        payInput: "",
        //错误支付次数
        payCount: 0,
        //验证码
        codeImage:"",
        //验证码输入
        payCode:"",

        //确认订单提示
        ordersAlertTitle:'',
        //确认订单提示类型
        ordersAlertType:'',
        //确认订单类型(true:购买，false:租借)
        orderType:undefined,
        // orderType:true,
        //确认订单弹框
        ordersDialog:{
          title: "确认订单",
          width: 0,
          height: 360,
          visible: false,
        },
        //购买总价
        allBuyCost:'',
        //购买成功后返回的信息
        backBuyInfo:[],
        //租借成功后返回的信息
        backRentInfo:'',
        rentFormData:{
          //提取时间
          getTime:'',
          //租借数量
          rentNumber:1,
          //租借时长
          rent:1,
        },
        //时间范围
        timeRange:'',
        rentRules: {
          rentNumber:{type:'number', required: true, trigger: "change", message: "请输入租借数量" },
          rent:{type:'number', required: true, trigger: "change", message: "请输入租借时长" },
          getTime:{required: true, trigger: "change", message: "请选择租取时间" }
        },

        buyFormData:{
          //购买数量
          buy:1,
        },
        buyRules:{buy:{type:'number', required: true, trigger: "change", message: "请输入购买数量" }},
        //器材信息
        equipmentInfo:'',
        //器材图片
        picList:[],
        //器材详细弹框
        DDialog:{
          title:'',
          width:800,
          height:520,
          visible: false,
        },
        //资产id
        assetId: "",
        //用户金额
        balance: 0,
        //用户所有积分
        allPoint: 0,
        //用户此次订单可用积分
        canUsePoint:0,
        //将使用积分
        point: 0,

        //未找到器材图片
        notFoundEquipmentPic,
        //器材列表
        equipmentListData: [],
        //查询条件
        searchCondition :{
          page: 1,
          pageSize: 10,
          cid: "",
          searchContent: ""
        },
        //分页容量
        paginationSize: [6,10,12,18,24],
        //查询返回 总记录数
        totalPage: 0,
        //现有运动类别
        categories: [],
      }
    },
    created(){
      this.getBagNumber();
      this.getFirstEquipmentList();
    },
    methods:{
      //创建订单
      async onOrdersConfirm(){
        clearTimeout(this.comOrderTimeOut);
        let ordersCost;
        let ordersType;
        let arr = [];
        if(this.orderType){
          ordersCost = this.allBuyCost;
          ordersType = 2;
          this.backBuyInfo.forEach(item=>{arr.push(item.id)});
        }else{
          ordersCost = this.allCost;
          ordersType = 1;
          arr.push(this.backRentInfo.id);
        }
        this.paycost = ordersCost
        let parm = {
          uid: this.$store.getters.userId,
          cost: ordersCost,
          point: this.point,
          type: ordersType,
          iid: arr
        }

        let res = await addNewOrdersApi(parm);
        if(res&&res.code==200){
          if(this.bagDialog.visible&&!this.DDialog.visible){
            this.deleteBag(false);
          }
          this.newOrders = res.data;
          this.ordersDialog.visible = false;
          this.point = 0;
          this.onClose();
          if(ordersCost==0&&this.point==0){
            this.finishPay();
          }else{
            this.openPayDialog();
          }
        }
      },
      //打开支付弹框
      openPayDialog(){
        this.$refs.payDialogRef.canConfirm = true;
        this.payDialog.visible = true;
        this.payTimeOut = setTimeout(()=>{
          this.autoPayClose();
        },1000*60*10)
        this.ordersStopCountDown = Date.now() + 10 * 1000 * 60;
      },
      //密码框值
      getPayInputValue(value){
        this.payInput = value;
      },
      //获取四则运算验证码
      async getMathCodeImage(){
        this.codeImage = await getMathCodeImageApi();
      },
      //自动关闭支付弹框
      autoPayClose(){
        if(this.payDialog.visible){
          this.payDialog.visible = false;
          this.$message.info("支付超时已自动取消订单");
          this.payCount = 0;
          this.$refs.payInputRef.cleanInput();
        }
      },
      //关闭支付弹框
      async onPayClose(){
        let confirm = await this.$myconfirm("关闭后仍可以在订单中心支付");
        if(confirm){
          clearTimeout(this.payTimeOut);
          this.payDialog.visible = false;
          this.payCount = 0;
          this.$refs.payInputRef.cleanInput();
        }
      },
      //提交支付信息
      onPayConfirm(){
        if(this.payCount<3){
          this.checkAssetPayKey();
        }else{
          this.checkMathCode();
        }
        if(this.payCount==2){
          this.getMathCodeImage();
        }
      },
      //发起校验密码
      async checkAssetPayKey(){
        let res = await checkAssetKeyApi({id:this.assetId,assetKey:this.payInput}).catch(()=>{
          this.payCode='';
          this.payCount++
        });
        if(res&&res.code==200){
          clearTimeout(this.payTimeOut);
          this.finishPay();
          this.payDialog.visible = false;
        }
        this.$refs.payInputRef.cleanInput();
      },
      //输错三次密码，验证码
      async checkMathCode(){
        let res = await checkMathCodeApi({mathCode:this.payCode}).catch(()=>{
          this.payCode='';
        }).finally(this.getMathCodeImage())
        if(res&&res.code==200){
          this.checkAssetPayKey();
        }
      },
      //完成支付
      async finishPay(){
        let res = await finishPayApi(this.newOrders);
        if(res&&res.code==200){
          this.$message.success(res.msg)
          this.payCount = 0;
          this.$refs.payInputRef.cleanInput();
        }
      },

      //移除器材袋
      async deleteBag(flag){
        let arr = [];
        this.selectTableRow.forEach(item=>{
          arr.push(item.id);
        })
        let res = await deleteBagApi({ids:arr.toString()});
        if(res&&res.code==200){
          if(flag){
            this.$message.success(res.msg);
          }
          this.getBagNumber().then((data)=>{
            if(data>0){
              this.getEquipmentBag();
            }else{
              //因移除关闭时不必保存
              this.selectTableRow = [];
              this.bagDialog.visible = false;
            }
          });
        }
      },
      //当器材数量改变时
      changeCount(row){
        this.bagCost = 0;
        this.selectTableRow.map(item=>{
          if(row.id==item.id){
            item.number = row.number;
            if(item.number!=null||item.number!=''){
              item.cost = item.price*item.number;
            }
          }
        })
      },
      //获取选择表格项
      selectTable(selection){
        this.selectTableRow = [];
        selection.map(item=>{
          if(item.number!=null){
            item.cost = item.price*item.number;
          }
        })
        this.selectTableRow = selection;
      },
      //确认购买
      async onbagConfirm(){
        let res = await addEquipmentBuyApi(this.selectTableRow).catch(res=>{console.log(res)});
        if(res&&res.code==200){
          this.backBuyInfo = res.data;
          if(res.data.length==this.selectTableRow.length){
            this.ordersAlertType='success'
          }else{
            this.ordersAlertType='warning'
          }
          if(this.backBuyInfo.length>0){
            this.orderType = true;
            this.getUserAsset();
            this.ordersAlertTitle = res.msg;
            this.ordersDialog.width = 700;
            this.ordersDialog.visible = true;
            this.comOrderTimeOut = setTimeout(()=>{
              this.autoOnOrdersClose();
            },1000*60)
          }
        }
      },
      //关闭器材袋
      async onbagClose(){
        if(this.bagList.length>0){
          let updateArr = [];
          this.bagList.forEach(item=>{
            const {id,uid,eid,number} = item
            updateArr.push({id,uid,eid,number})
          })
          let res = await editEquipmentBagApi(updateArr);
          if(res&&res.code==200){
            this.bagDialog.visible = false;
          }
        }
        this.selectTableRow = [];
        this.bagDialog.visible = false;
      },
      //打开器材袋
      openBag(){
        if(this.bagNumber>0){
          this.getEquipmentBag();
          this.bagDialog.visible = true;
        }else{
          this.$message.info("器材袋空荡荡的！");
        }
      },
      //获取器材袋信息
      async getEquipmentBag(){
        let res = await getEquipmentBagInfoApi({uid:this.$store.getters.userId});
        if(res&&res.code==200){
          this.bagList = res.data;
        }
      },
      //获取器材袋的数量
      async getBagNumber(){
        let res = await getEquipmentBagNumberApi({uid:this.$store.getters.userId});
        if(res&&res.code==200){
          this.bagNumber = res.data;
        }
        return res.data;
      },
      //放入器材袋
      async putBag(){
        let parm = {
          uid:this.$store.getters.userId,
          eid:this.equipmentInfo.id,
          cost:this.buyPay,
          number:this.buyFormData.buy
        }
        let res = await addEquipmentBagApi(parm);
        if(res&&res.code==200){
          if(res.data){
            this.$message.success(res.msg);
            //放入后关闭器材详细页
            this.onClose();
          }else{
            //器材袋满
            this.$message.info(res.msg);
            this.getEquipmentById(this.equipmentInfo.id);
          }
          this.getBagNumber();
        }
      },
      //点击确认购买
      conBuy(){
        this.$refs.buyFormRef.validate(async (valid) => {
          let parm = {
            uid:this.$store.getters.userId,
            eid:this.equipmentInfo.id,
            cost:this.buyPay,
            number:this.buyFormData.buy
          }
          let arr = [];
          arr.push(parm);
          if (valid) {
            let res = await addEquipmentBuyApi(arr).catch(res=>{console.log(res)});
            if(res&&res.code==200){
              this.backBuyInfo = res.data;
              if(res.data.length==arr.length){
                this.ordersAlertType='success'
              }else{
                this.ordersAlertType='warning'
              }
              if(this.backBuyInfo.length>0){
                this.orderType = true;
                this.getUserAsset();
                this.ordersAlertTitle = res.msg;
                this.ordersDialog.width = 700;
                this.ordersDialog.visible = true;
                this.comOrderTimeOut = setTimeout(()=>{
                  this.autoOnOrdersClose();
                },1000*60)
              }
            }
          }
        })
      },
      //计算订单总价
      getSummaries({ columns, data }){
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '总价';
            return;
          }
          if (index === columns.length - 1) {
            const values = data.map(item => Number(item[column.property]));
            if (!values.every((value,i) => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                  return  prev + curr;
                } else {
                  return prev;
                }
              }, 0);
              let allCost = sums[index];
              if(this.point!=null&&this.point>0){
                this.allBuyCost = (allCost - this.point/1000);
              }else{
                this.allBuyCost = allCost
              }
              if(this.allBuyCost>0){
                sums[index] = this.allBuyCost.toFixed(2)+' 元';
              }else{
                sums[index] = '免费'
              }
            }
          }
        });
        return sums;
      },

      //检验是否有超时未归还器材
      async checkOutTime(flag){
        let res = await checkOutTimeApi({uid:this.$store.getters.userId});
        if(res&&res.code==200){
          if(res.data==0){
            if(flag==0){
              this.conRent();
            }else if(flag==1){
              this.conBuy();
            }else if(flag==2){
              this.onbagConfirm();
            }
          }else if(res.data>0){
            this.$message.error("请先归还已租赁超时的器材！");
          }
        }
      },


      //关闭确认订单
      async onOrdersClose(){
        let confirm = await this.$myconfirm("确定取消此订单建立吗？");
        if (confirm) {
          let res = null;
          if(this.orderType){
            let deleteArr = [];
            this.backBuyInfo.forEach(item=>{deleteArr.push(item.id)});
            res = await deleteEQBuyApi({ids:deleteArr.toString()});
          }else{
            res = await deleteEQRentApi({id:this.backRentInfo.id});
          }
          if(res&&res.code==200){
            this.ordersDialog.visible = false;
            this.point = 0;
            this.$message.info(res.msg);
            if(this.orderType){
              if(this.bagDialog.visible&&!this.DDialog.visible){
                //todo
              }else if(this.DDialog.visible&&!this.bagDialog.visible){
                this.getEquipmentById(this.equipmentInfo.id);
              }
            }else{
              this.getEquipmentById(this.backRentInfo.eid);
            }
          }
        }
      },
      //点击确认租借
      conRent(){
        this.$refs.rentFormRef.validate(async (valid) => {
          if (valid) {
            let backTime =  this.timestampToTime(new Date(this.rentFormData.getTime).getTime()+this.rentFormData.rent*60*60*1000+60*10*1000);
            let parm = {
              uid:this.$store.getters.userId,
              eid:this.equipmentInfo.id,
              cost:this.rentPay,
              number:this.rentFormData.rentNumber,
              times:this.rentFormData.rent,
              getTime:this.rentFormData.getTime,
              backTime
            }
            let res = await addEquipmentRentApi(parm);
            if(res&&res.code==200){
              this.ordersAlertTitle = res.msg;
              this.backRentInfo = res.data;
              if(this.backRentInfo!=null){
                this.orderType = false;
                this.getUserAsset();
                this.ordersDialog.width = 420;
                this.ordersDialog.visible = true;
                this.comOrderTimeOut = setTimeout(()=>{
                  this.autoOnOrdersClose();
                },1000*60)
              }
            }
          }
        });
      },
      //时间戳转日期
      timestampToTime(timestamp) {
        var date = new Date(timestamp);
        var Y = date.getFullYear() + "-";
        var M =
          (date.getMonth() + 1 < 10
            ? "0" + (date.getMonth() + 1)
            : date.getMonth() + 1) + "-";
        var D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
        var h = date.getHours() + ":";
        var m = date.getMinutes() + ":";
        var s = date.getSeconds();
        return Y + M + D + h + m + s;
      },
      //若用户超1分钟停留在确认页面自动关闭
      async autoOnOrdersClose(){
        if(this.ordersDialog.visible){
          let res = null;
          if(this.orderType){
            res = await deleteEQBuyApi({ids:this.backBuyInfo});
          }else{
            res = await deleteEQRentApi({id:this.backRentInfo.id});
          }
          if(res&&res.code==200){
            this.ordersDialog.visible = false;
            this.point = 0;
            this.$message.info("确认超时自动取消建立订单");
            clearTimeout(this.comOrderTimeOut);
            if(this.orderType){
              let deleteArr = [];
              this.backBuyInfo.forEach(item=>{deleteArr.push(item.id)});
              res = await deleteEQBuyApi({ids:deleteArr.toString()});
            }else{
              this.getEquipmentById(this.backRentInfo.eid);
            }
          }
        }
      },
      //获取用户资产信息
      async getUserAsset(){
        let res = await getAssetByUid({uid:this.$store.getters.userId});
        if(res&&res.code==200){
          this.assetId = res.data.id
          this.allPoint = res.data.point;
          this.balance = res.data.balance;
          let allcost;
          this.orderType ? allcost=this.allBuyCost : allcost=this.backRentInfo.cost;
          if(this.allPoint/1000>allcost){
            this.canUsePoint = allcost*1000;
          }else{
            this.canUsePoint = this.allPoint;
          }
        }
      },
      //详细页关闭
      onClose(){
        this.rentFormData.getTime = '';
        this.rentFormData.rentNumber = 1;
        this.rentFormData.rent = 1;
        this.buyFormData.buy = 1;
        this.equipmentInfo = '';
        this.picList = [];
        this.DDialog.visible = false;
      },
      //打开器材详细页
      showEquipmentDetails(e){
        let d = new Date();
        let h = d.getHours();
        let m = d.getMinutes()+3;
        let s = d.getSeconds();
        h>=7 ? '' : h=7;
        this.timeRange = h+':'+m+':'+s+' - 20:00:00'
        this.getEquipmentById(e.id);
        this.DDialog.title = '器材 '+e.name+' 详情';
        this.DDialog.visible = true;
      },
      //获取器材新信息
      async getEquipmentById(id){
        let res = await getEquipmentApi({id:id});
        if(res&&res.code==200){
          this.equipmentInfo = res.data;
          this.getPicturesByBid(this.equipmentInfo.equipmentNo)
        }
      },
      //获取器材图片
      async getPicturesByBid(bid){
        let res = await getPicturesByBidApi({"bid":bid})
        if(res&&res.code==200){
          this.picList = [];
          res.data.forEach(item => { this.picList.push(item.url) });
        }
      },
      //分类查询
      tabClick(tab){
        this.searchCondition.cid = this.categories[tab.name].cid;
        this.getEquipmentList();
      },
      //内容查询
      getSearchContent(val){
        this.searchCondition.searchContent = val;
        this.getEquipmentList();
      },
      //分页查询getPagination
      getPagination(val){
        this.searchCondition.page = val.page;
        this.searchCondition.pageSize = val.limit;
        this.getEquipmentList();
      },
      //获取器材列表
      async getEquipmentList() {
        let res = await getValidEquipmentListApi(this.searchCondition);
        if (res && res.code == 200) {
          this.totalPage = res.data.total;
          this.equipmentListData = res.data.list
        }
      },
      //初始化获取器材列表
      async getFirstEquipmentList() {
        let res = await getValidEquipmentListApi();
        if (res && res.code == 200) {
          this.totalPage = res.data.total;
          this.equipmentListData = res.data.list;
          this.categories = [];
          this.categories = this.arrUnique(this.equipmentListData)
          this.categories.unshift({cid:'',label:'全部'});
          this.categories.push({cid:0,label:'其它'});
        }
      },
      //对象数组去重
      arrUnique(arr){
          let ojb = {};
          arr = arr.reduce(function(prevArr, currentItem) {
              ojb[currentItem.cid] ? '' : ojb[currentItem.cid] = true && prevArr.push(currentItem);
              return prevArr
          }, [])
          arr = arr.filter(item=>{
            return item.cid!=null
          })
          return arr;
      },
    },
    computed:{
      rentPay(){
        if(this.rentFormData.rent!=null&&this.rentFormData.rentNumber!=null){
          if(this.rentFormData.rent>=24){
            let t = this.rentFormData.rent%24;
            let d = Math.floor(this.rentFormData.rent/24);
            return  ((d*(this.equipmentInfo.rentCost*24*0.5)+t*this.equipmentInfo.rentCost)*this.rentFormData.rentNumber).toFixed(2);
          }else{
            return (this.rentFormData.rent*this.equipmentInfo.rentCost*this.rentFormData.rentNumber).toFixed(2)
          }
        }
        return '-';
      },
      buyPay(){
        if(this.buyFormData.buy!=null){
          return (this.buyFormData.buy*this.equipmentInfo.buyCost).toFixed(2);
        }
        return '-';
      },
      allCost(){
        if(this.point>0){
          return this.backRentInfo.cost - this.point/1000;
        }else{
          return this.backRentInfo.cost;
        }
      },
      bagListCost(){
        let bagCost = 0;
        if(this.selectTableRow.length>0){
          this.selectTableRow.forEach(item=>{
            bagCost += item.cost;
          })
        }
        return bagCost;
      }
    },
    filters:{
      showCost(val){
        if(val==0) {
          return '免费'
        }else{
          return '¥ '+val
        }
      },
      showTime(val){
        if(val>=24){
          let t = val%24;
          let d = Math.floor(val/24);
          if(t!=0){
            return d+' 天 '+t+' 小时'
          }else{
            return d+' 天'
          }
        }else{
          return val+' 小时'
        }
      },
      bagShowCost(val,row){
        val = (row.number*row.price).toFixed(2);
        if(val>0){
          return '¥ '+val;
        }else if(val==0){
          return '免费';
        }
      }
    },
    watch:{
      payInput(val){
        if(val.length>=6){
          this.$refs.payDialogRef.canConfirm = false;
        }else{
          this.$refs.payDialogRef.canConfirm = true;
        }
      },
    }
  }
</script>

<style lang="scss" scoped>
  ::v-deep .el-tabs__item{
    width: 80px;
  }
  ::v-deep .el-tabs--left .el-tabs__item.is-left{
    text-align:center;
  }
  .listRow{
    height: 66vh;
    padding:20px;
    overflow-y: scroll;
  }
  .card{
    width: 220px;
    height: 300px;
    margin: 10px 20px 20px 20px;
    border-radius:4px;
    box-shadow: 1px 3px 9px #ccc;
    transition: 0.3s;
    cursor: pointer;
    overflow: hidden;
    &:hover{
      box-shadow: 3px 2px 18px #ccc;
      transition: 0.3s;
    }
    .fieldCover{
      height: 200px;
      background-repeat:no-repeat;
      background-position:center;
      background-size:cover;

    }
    .eInfo{
      padding: 15px 0 15px 10px;
      .eTitle{
        color: #303133;
        font-size: 26px;
        font-weight: bold;
        margin-bottom: 16px;
      }
      .buyprice,.rentprice {
        color:red;
        font-size: 24px;
        font-weight: bold;
        padding: 0 5px;
        overflow: hidden;
        span{
          color: #909399;
          font-size: 14px;
        }
        .buycost,.rentcost{
          display: inline-block;
          vertical-align: middle;
          color: #F2F6FC;
          text-align: center;
          font-size: 14px;
          font-weight: normal;
          background-color: #67C23A;
          border-radius: 5px;
          height: 20px;
          width: 20px;
          line-height: 20px;
          margin-right: 3px;
          margin-bottom: 5px;
        }
        .rentcost{
            background-color: #E6A23C;
        }
      }
    }

  }
  .fieldPic{
    height: 300px;
    background-repeat:no-repeat;
    background-position:center;
    background-size:cover;
    border-radius: 6px;
  }
  .infoTitle{
    color:#303133;
    font-size: 24px;
    font-weight: bold;
    margin: 20px 0px;
  }
  .infoRemark{
    color: #606266;
    font-size: 18px;
    line-height: 28px;
    margin: 10px 0px;
    span{
      color:#505153;
      font-weight: bold;
    }
  }
  .formStyle{
    span{
      font-size: 24px;
    }
  }
  .countCost{
    color: red;
    font-weight: bolder;
    font-size:26px;
  }

  .tiptext{
    margin-bottom: 20px;
    font-size: 14px;
    color: #606266;
  }

  .codeImg {
    width: 100%;
    height: 36px;
    padding: 5px 0;
    border: 1px solid #ddd;
  }
</style>
